package com.email.box.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.spec.SecretKeySpec;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 转换工具类
 */
public class ConvertUtil {

    private static final String PROD_KEY = "AGEGG12DGHR@#DGW";
    private static final String DEV_KEY = "AGEGG12DGHR@#csq";

    //Object转Map
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getObj2Map(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        Map<String, Object> map = new LinkedHashMap();
        try {
            map = mapper.readValue(mapper.writeValueAsString(object), Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        map.remove("page");
        map.remove("limit");
        map.remove("order");
        map.remove("search_field");
        map.remove("search_type");
        map.remove("search_word");
        map.remove("response_field");
        return map;
    }

    /**
    * 解密AES密文
    * @param bytes 密码密文
    * @param env 应用运行环境
    * @return 密码明文
    */
    public static String decryptAESPwd(byte[] bytes, String env){
        byte[] encodedKey = getEncodedKey(env);
        AES aes = SecureUtil.aes(encodedKey);
        byte[] decrypt = aes.decrypt(bytes);
        return new String(decrypt);
    }


    /**
     * 加密密码明文
     * @param content 密码明文
     * @param env 应用运行环境
     * @return 密码密文
     */
    public static byte[] encryptAESPwd(String content, String env) {
        byte[] encodedKey = getEncodedKey(env);
        AES aes = SecureUtil.aes(encodedKey);
        return aes.encrypt(content);
    }

    /**
     * 获取加密后的秘钥
     * @param env 应用运行环境
     * @return 加密后的秘钥
     */
    private static byte[] getEncodedKey(String env) {
        String key = env.equals("1") ? PROD_KEY : DEV_KEY;
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(),"AES");
        return SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), keySpec).getEncoded();
    }

}
